<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>菜单管理</title>
    <link rel="stylesheet" href='/plug-in/pear/css/pear.css' media="all">
    <link rel="stylesheet" href='/css/base.css'>
    <script src="/plug-in/jquery/jquery-3.5.1.min.js" charset="utf-8"></script>
    <script src='/plug-in/layui/layui.js' charset="utf-8"></script>
    <script src='/plug-in/lay-config.js' charset="utf-8"></script>
    <style>
        .layui-btn-container .layui-btn {
            margin-bottom: 0;
        }
        .add-menu-form{
            display: none;
            padding: 45px;
        }
        .layui-iconpicker-icon{
            background-color: transparent !important;
        }
    </style>
</head>
<body>
<div class="page-content" shiro:hasPermission="system.menu.list">
    <table id="menuTreeTb"></table>
</div>

<div class="add-menu-form">
    <form class="layui-form" action="" lay-filter="add-menu" style="width: 500px; margin: 0 auto;">
        <div class="layui-form-item" id="parent-menu">
            <label class="layui-form-label towexin-form-label">上级菜单：</label>
            <div class="layui-input-block">
                <div id="setAuthority" style="margin-right: 2px;" class="xm-select-demo"></div>
            </div>
        </div>
        <div class="layui-form-item" id="switch">
            <label class="layui-form-label towexin-form-label">页面：</label>
            <div class="layui-input-block">
                <input type="checkbox" name="page" lay-skin="switch" lay-filter="switchIsPage" lay-text="是|否">
            </div>
        </div>
        <div class="layui-form-item m-name layui-hide">
            <div class="layui-input-block">
                <input type="text" name="pid" class="layui-input">
                <input type="text" name="id" class="layui-input">
                <input type="text" name="type" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item m-name">
            <label class="layui-form-label towexin-form-label layui-required" id="showName">名称：</label>
            <div class="layui-input-block">
                <input type="text" name="menuName" lay-verify="required" autocomplete="off" placeholder="请输入名称" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item m-href layui-hide" id="showUrl">
            <label class="layui-form-label towexin-form-label layui-required">页面URL：</label>
            <div class="layui-input-block">
                <input type="text" name="menuHref" lay-verify="menuHref" placeholder="请输入页面URL" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item m-hre">
            <label class="layui-form-label towexin-form-label">菜单图标：</label>
            <div class="layui-input-block">
                <input type="text" name="icon" id="iconPicker" lay-filter="iconPicker" style="display:none;">
            </div>
        </div>
        <div class="layui-form-item m-href">
            <label class="layui-form-label towexin-form-label">排序：</label>
            <div class="layui-input-block">
                <input type="number" name="sort" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item m-name">
            <label class="layui-form-label towexin-form-label">target属性：</label>
            <div class="layui-input-block">
                <input type="radio" name="target" value="_self" title="_self (选项卡)">
                <input type="radio" name="target" value="_blank" title="_blank (新窗口)">
            </div>
        </div>
<!--        <div class="layui-form-item m-name">-->
<!--            <label class="layui-form-label towexin-form-label">菜单图标：</label>-->
<!--            <div class="layui-input-block">-->
<!--                <input type="text" id="menuIcon" lay-filter="menuIcon" name="ficon" style="display:none;">-->
<!--            </div>-->
<!--        </div>-->

        <div class="layui-form-item">
            <div class="layui-input-block" style="text-align: right;">
                <button type="submit" id="submit-type" class="pear-btn pear-btn-primary" lay-submit="" lay-filter="add">立即提交</button>
            </div>
        </div>
    </form>
</div>

<!-- 操作列 -->
<script type="text/html" id="auth-state">
    <button shiro:hasPermission="system.menu.edit" class="layui-btn layui-btn-success layui-btn-xs" lay-event="edit">编辑</button>
    <button shiro:hasPermission="system.menu.delete" class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</button>
    {{#  if(d.menuHref=="" || d.menuHref==null){ }}
    <button shiro:hasPermission="system.menu.add" class="layui-btn layui-btn-normal layui-btn-xs" lay-event="add">添加下级</button>
    {{#  } }}
</script>
<script type="text/html" id="toolbarTop">
    <div class="layui-btn-container">
        <button shiro:hasPermission="system.menu.list" class="layui-btn layui-btn-sm layui-bg-black" lay-event="refresh"><span class="fa fa-refresh" title="刷新表格" aria-hidden="true"></span></button>
        <button shiro:hasPermission="system.menu.add" class="layui-btn layui-btn-sm layui-bg-blue" lay-event="newModel"><span class="fa fa-plus-circle" aria-hidden="true"></span> 添加</button>
    </div>
</script>
<script type="text/html" id="status">
    <input shiro:hasPermission="system.menu.status" type="checkbox" lay-skin="switch" {{d.status===true?"checked":""}} lay-filter="status" lay-text="启用|禁用" value="{{d.id}}">
    <input shiro:lacksPermission="system.menu.status" disabled type="checkbox" lay-skin="switch" {{d.status===true?"checked":""}} lay-text="启用|禁用">
</script>
<script type="text/javascript" th:inline="none" shiro:hasPermission="system.menu.list">
    layui.use(["treeTable", "xmSelect", "iconPicker"], function(){
        let form = layui.form, layer=layui.layer, treeTable = layui.treeTable, element=layui.element, xmSelect=layui.xmSelect, iconPicker = layui.iconPicker;

        // 渲染树形表格
        var menuTb = treeTable.render({
            elem: '#menuTreeTb',
            toolbar: "#toolbarTop",
            defaultToolbar: false,
            skin: "line",
            tree: {
                iconIndex: 0,           // 折叠图标显示在第几列
                isPidData: true,        // 是否是id、pid形式数据
                idName: 'id',  // id字段名称
                pidName: 'pid',     // pid字段名称
                getIcon: function(d) {  // 自定义图标
                    // d是当前行的数据
                    if (d.pid=="no" && d.type != "1") {  // 判断是否有子集
                        return '<i class="fa fa-window-maximize" aria-hidden="true"></i>';
                    } else if(d.type == "1"){
                        return '<i class="fa fa-home" aria-hidden="true"></i>'
                    } else {
                        if(d.menuHref != "" && d.menuHref!=null){
                            return '<i class="fa fa-link" aria-hidden="true"></i>';
                        }else{
                            return '<i class="fa fa-cog" aria-hidden="true"></i>';
                        }
                    }
                }
            },
            cols: [[
                // {type: 'numbers'},
                // {type: 'checkbox'},
                {field: 'menuName', title: '菜单名称', width: 300},
                {
                    width: 80, align: 'center', templet: function (d) {
                        if (d.pid === "no" && d.type !== "1") {
                            return '<span class="layui-badge layui-bg-black">模块</span>';
                        }else if(d.type !== "1"){
                            if (d.menuHref !== "" && d.menuHref!=null) {
                                return '<span class="layui-badge layui-bg-gray">页面</span>';
                            } else {
                                return '<span class="layui-badge-rim">菜单</span>';
                            }
                        }else{
                            return '<span class="layui-badge layui-bg-blue">首页</span>';
                        }
                    }, title: '类型'
                },
                {title: '默认展开', width: 100, align: "center", templet: function (d) {
                    if (d.menuHref !== "") return
                    return '<input type="checkbox" value="'+d.id+'" lay-skin="switch" lay-text="true|false" lay-filter="open-switch" '+(d.open?"checked":"")+'>'
                }},
                {
                    title: "图标", width: 60, align: 'center', templet: function (d) {
                        return '<i class="layui-icon '+d.icon+'"></i>';
                    }
                },
                {field: 'menuHref', title: '菜单链接'},
                {title: '状态', width: 100, templet: "#status"},
                {field: "sort", title: "排序", width: 80, align: "center", sort: true},
                {field: "createdTime", width: 180, sort: true, title: '创建时间',},
                {field: "updateTime", width: 180, sort: true, title: '修改时间',},
                {templet: '#auth-state', width: 200, unresize: false, align: 'left', title: '操作'},
            ]],
            //height: "full-40",
            reqData: function(data, callback) {
                $.ajax({
                    url: "/menu/selectAll",
                    success:function(res){
                        callback(res.data);
                    },
                })
            },
            done: function(){
                element.render('nav');
                $(".ew-tree-table-head .layui-table").width($(".ew-tree-table-box .layui-table").width())
            }
        });

        window.onresize = function(){
            $(".ew-tree-table-head .layui-table").width($(".ew-tree-table-box .layui-table").width())
        }

        // 头部工具栏点击事件
        treeTable.on('toolbar(menuTreeTb)', function (obj) {
            setAuthority.changeExpandedKeys(true)
            switch (obj.event) {
                case 'newModel':
                    $('input[name=target]').prop('checked', false);
                    form.render('radio');
                    $("#showUrl").addClass("layui-hide")
                    setAuthority.setValue([])
                    form.val("add-menu",{
                        pid: "",
                        id: "",
                        type: "0",
                        menuName: "",
                        menuHref: "",
                        sort: "",
                        page: false,
                        target: "",
                        icon: "layui-icon-component"
                    });
                    iconPicker.checkIcon('iconPicker', 'layui-icon-component')
                    layer.open({
                        type: 1,
                        area: ["100%", '100%'],
                        maxmin: true,
                        content: $(".add-menu-form"),
                        title: "新增菜单",
                        scrollbar: false
                    })
                    break;
                case "refresh":
                    menuTb.reload()
            }
        });

        //监听工具条
        treeTable.on('tool(menuTreeTb)', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;

            setAuthority.changeExpandedKeys(true)

            if (layEvent === 'del') {
                layer.confirm('确定删除 <span style="color: red; font-weight: 800">'+data.menuName+'</span> 么？', {icon: 3, title:'提示'}, function(index){
                    layer.close(index);
                    layer.load()
                    $.ajax({
                        url: '/menu/deleteOne',
                        data: {id: data.id},
                        success: function(result) {
                            if (result.code == 200) {
                                menuTb.reload();
                                getMenuTree()
                                layer.closeAll('loading')
                                layer.msg("删除成功")
                            } else {
                                layer.closeAll('loading')
                                layer.msg("删除失败")
                            };
                        },
                        error: function() {
                            layer.closeAll('loading')
                            layer.msg("服务错误")
                        }
                    });
                });
            } else if (layEvent === 'edit') {
                $('input[name=target]').prop('checked', false);
                form.render('radio');
                data.page===true?$("#showUrl").removeClass("layui-hide"):$("#showUrl").addClass("layui-hide")
                setAuthority.setValue([data.pid]);
                form.val("add-menu",data)
                if (data.icon!==""&&data.icon!==null){
                    iconPicker.checkIcon('iconPicker', data.icon)
                }else {
                    iconPicker.checkIcon('iconPicker', 'layui-icon-star-fill')
                }
                layer.open({
                    type: 1,
                    area: ["100%", '100%'],
                    maxmin: true,
                    content: $(".add-menu-form"),
                    title: "编辑菜单",
                    scrollbar: false
                })
                // layer.msg('修改' + data.mId);
            } else if(layEvent === 'add'){
                $('input[name=target]').prop('checked', false);
                form.render('radio');
                $("#showUrl").addClass("layui-hide")
                setAuthority.setValue([data.id])
                form.val("add-menu",{
                    pid: data.id,
                    id: "",
                    type: "0",
                    menuName: "",
                    menuHref: "",
                    sort: "",
                    page: false,
                    target: "",
                    icon: "layui-icon-component"
                });
                iconPicker.checkIcon('iconPicker', 'layui-icon-component')
                layer.open({
                    type: 1,
                    area: ["100%", '100%'],
                    maxmin: true,
                    content: $(".add-menu-form"),
                    title: "新增模块",
                    scrollbar: false
                })
            }
        });

        // 监听展开开关
        form.on('switch(open-switch)', function(obj){
            layer.load()
            $.ajax({
                url: "/menu/openStatus",
                data: {id: this.value, open: obj.elem.checked},
                success(res){
                    layer.closeAll("loading")
                    if(res.code === 200){
                        obj.elem.checked?layer.tips("默认展开", obj.othis):layer.tips("默认折叠", obj.othis)
                    }else {
                        layer.tips("操作无效", obj.othis)
                    }
                },
                error(err){
                    layer.closeAll("loading")
                    layer.tips("操作无效", obj.othis)
                    console.log(res)
                }
            })
        });

        //监听状态操作
        form.on('switch(status)', function(obj){
            layer.load()
            $.ajax({
                url: "/menu/changeStatus",
                data: {id: obj.value, status: obj.elem.checked},
                success: function (res) {
                    if (res.code === 200) {
                        layer.closeAll()
                        layer.tips("操作成功", obj.othis);
                    } else if(res.code === 401){
                        layer.closeAll()
                        layer.tips(res.msg, obj.othis);
                    }else {
                        layer.closeAll('loading')
                        layer.tips("操作失败", obj.othis);
                    }
                    menuTb.refresh();
                },
                error(){
                    layer.closeAll('loading')
                    layer.msg("服务出错")
                }
            })
        });

        form.on('submit(add)', function(data){
            data.field.pId = data.field.pid
            if(data.field.page && data.field.page=="on"){
                data.field.page = true
            }else{
                data.field.page = false
                data.field.menuHref = ""
            }
            layer.load()
            $.ajax({
                url: data.field.id!==null&&data.field.id!==""?"/menu/update":"/menu/save",
                type: "POST",
                data: data.field,
                success: function (res) {
                    if (res.code == 200) {
                        menuTb.refresh();
                        getMenuTree()
                        layer.closeAll()
                        layer.msg("操作成功")
                    } else {
                        layer.closeAll('loading')
                        layer.msg("操作失败")
                    };
                },
                error: function() {
                    layer.closeAll('loading')
                    layer.msg("服务出错")
                }
            })
            return false;
        });

        iconPicker.render({
            elem: '#iconPicker',
            type: 'fontClass',
            search: true,
            page: true,
            limit: 16,
            click: function(data) {
                form.val("add-menu", data)
            }
        });

        //监听指定开关
        form.on('switch(switchIsPage)', function(data){
            if(this.checked){
                $("#showUrl").removeClass("layui-hide")
            }else{
                $("#showUrl").addClass("layui-hide")
            }
        });

        form.verify({
            menuHref: function(value, item){ //value：表单的值、item：表单的DOM对象
                if (form.val("add-menu").page){
                    if (value.replace(/\s/g, "") === ""){
                        return "必填项不能为空"
                    }
                }
            }
        });


        var setAuthority = xmSelect.render({
            el: '#setAuthority',
            autoRow: true,
            name: "authorityList",
            tips: '请选择上级菜单',
            searchTips: '搜索菜单',
            filterable: true,
            layVerify: "required",
            direction: 'down',
            prop: {
                name: 'title'
            },
            tree: {
                show: true,
                showFolderIcon: true,
                showLine: true,
                indent: 35,
                expandedKeys: ["0"],
                //是否严格遵守父子模式
                strict: false,
                //是否开启极简模式
                simple: false,
                clickCheck: true,
                clickExpand: false
            },
            radio: true,
            model: {
                type: 'absolute',
            },
            on: function(data){
                if(data.arr.length>0){
                    form.val("add-menu",{
                        pid: data.arr[0].value
                    });
                }
            },
            theme: {
                color: '#1c86bb',
            },
            toolbar: {
                show: true,
                list: ['ALL', 'REVERSE', 'CLEAR']
            },
            height: '300px',
        })

        getMenuTree()

        function getMenuTree() {
            $.ajax({
                url: '/menu/selectMenuTree',
                success: function(result) {
                    setAuthority.update({
                        data: result.data
                    })
                },
                error: function() {
                    layer.msg("服务错误")
                }
            });
        }

    })
</script>
</body>
</html>